package crm.model.studentPC;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Robot;
import java.awt.Toolkit;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;

import packages.ImagePackage;
import packages.MousePackage;
import crm.model.NetConst;
import crm.model.Setting;
import crm.model.studentPC.win.WindowList;
import crm.util.ErrorHandler;


public class StudentPcService {
    private static final long serialVersionUID = 1L;

    public static void main(String[] args) {
        new StudentPcService();
    }
    WindowList wList;
    Robot robot;
    LockThread lock ;
    ExitThread hook;
    ReceiveThread receive;
    SendThread send;
    VNCThread vnc;
    
    public boolean isConnected;

    public StudentPcService(){
        init();
        initThreads();
    }
    private void startVNC() {
    	vnc = new VNCThread();
    	vnc.start();

	}
    public void initThreads(){
    	isConnected = false;
        receive = new ReceiveThread(this);
        send = new SendThread(this);
        receive.start();
        send.start();
    }
    public void init(){
    	vnc = new VNCThread();
    	isConnected = false;
        wList = new WindowList();
        lock = new LockThread(wList);
        hook = new ExitThread();
        Runtime.getRuntime().addShutdownHook(hook);
        try {
            robot = new Robot();
        } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public void connect(InetAddress ip) {
        try {

            Socket s = new Socket(ip, Setting.getTransportPort());
            start(s);

        } catch (IOException e) {
            e.printStackTrace();
            ErrorHandler.showAndGoOnErrorMessage("Socketverbindung konnte nicht aufgebaut werden");
            initThreads();
        }

    }



    private void start(Socket s) {
        try{

            ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
            ObjectInputStream is = new ObjectInputStream (s.getInputStream());

            hook.setSocket(this, s);
            
            startVNC();
            
            while (!s.isClosed()){
            	isConnected = true;
                int request = (Integer)is.readObject();
                System.out.println("Request: " + request);
                if (request == NetConst.CLOSE || request == -1){
                    is.close();
                    os.close();
                    s.close();
                    System.out.println("Stream closed");
                }else {

                    if (request == NetConst.SCREENSHOT){
                        os.writeObject(new ImagePackage());
                        os.reset();
                    }else if (request == NetConst.WINDOWS){
                        wList.refresh();
                        for(int i =0; i<wList.size(); i++){
                            os.writeObject(i);
                        }
                        os.writeObject(-1);
                        os.reset();
                    }else if (request == NetConst.MOUSESET){
                        MousePackage mp = (MousePackage)is.readObject();
                        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                        int x = (int)(mp.diffX * screenSize.width);
                        int y = (int)(mp.diffY * screenSize.height);
                        robot.mouseMove(x, y);
                    }else if (request == NetConst.LOGGEDUSER){
                        os.writeObject(System.getProperty("user.name"));
                    }else if (request == NetConst.SCREENLOCK){
                        lock = new LockThread(wList);
                        lock.lock();
                    }else if (request == NetConst.SCREENUNLOCK){
                        lock.unlock();
                    }else if (request == NetConst.WINDOWDATA){
                        Integer[] data = (Integer[]) is.readObject();
                        if (data[1] == NetConst.WNAME){
                            os.writeObject(wList.get(data[0]).getName());
                        }else if (data[1] == NetConst.WMAX){
                            wList.get(data[0]).maximized();
                        }else if (data[1] == NetConst.WMIN){
                            wList.get(data[0]).minimized();
                        }else if (data[1] == NetConst.WKILL){
                            wList.get(data[0]).endTask(true);
                        }
                    }else if (request == NetConst.MESSAGE){
                        String message = (String)is.readObject();
                        javax.swing.JOptionPane.showMessageDialog(null, message, "Message", javax.swing.JOptionPane.PLAIN_MESSAGE);
                    }else if (request == NetConst.STREAMTOALL){
                        Stream.show(is);
                    }else if (request == NetConst.WINDOWFOREGROUNDNAME){
                    	os.writeObject(wList.getAktivWindow().getName());
                    }
                }
            }
        }catch(SocketException e){
        	System.out.println("Connection resettet??");
        }catch(Exception e){
            e.printStackTrace();

        }finally {
            initThreads();
            vnc.closeVNC();
        }

    }



























}
